<template>
	<div
		class=" ac col h-vh overflow-scroll el-icon-caret-left
	bg-no-repeat object-cover min-h-screen-lg"
	>
		<div
			class="w-12/12 h-5xl 
			bg-gray-100 relative"
			@mouseover="showUpBg = true"
			@mouseleave="showUpBg = false"
		>
			<img
				:src="background | filterUrl()"
				alt=""
				class="w-12/12 h-12/12"
			/>

			<Upload
				action="Upload"
				:before-upload="handleBackgroundUpload"
				class="absolute bottom-sm right-md"
				v-show="showUpBg"
			>
				<Button icon="md-cloud-upload"></Button>
			</Upload>
		</div>
		<div class="text-center mt--3xl">
			<Avatar size="150" icon="ios-person" v-if="avatar.length == 0" />
			<Avatar :src="avatar" size="150" v-if="avatar.length != 0" />
			<h3>{{ nickName }}</h3>
			<h3>{{ selfintro }}</h3>
		</div>

		<div>
			<Button shape="circle" class="margin" @click.native="gotoEdit"
				>编辑</Button
			>
			<!-- <Button shape="circle" class="margin" icon="ios-search"></Button>
      <Button shape="circle" class="margin" icon="ios-search"></Button> -->
		</div>
		<Tabs value="Created">
			<TabPane label="拥有" name="Created">
				<HotBids :nftList="this.assets" />
			</TabPane>
			<TabPane label="在售" name="On sale">
				<HotBids :nftList="this.onSaleAssets" />
			</TabPane>
			<!-- <TabPane label="Collectibles" name="Collectibles"></TabPane>
			<TabPane label="Liked" name="Liked"></TabPane>
			<TabPane label="Following" name="Following"></TabPane>
			<TabPane label="Followers" name="Followers"></TabPane> -->
		</Tabs>
	</div>
</template>

<script>
import HotBids from '../components/HotBids';
import Web3 from 'web3';
import { NETWORKID, CONTRACTBUILD } from '@/config';
import OSS from 'ali-oss';

import { ststoken, getAuthorization } from '@/api';

export default {
	components: {
		HotBids,
	},
	filters: {
		filterUrl(url) {
			return /(\.jpeg|\.png|\.jpg|\.gif)$/i.test(url) ? url : '';
		},
	},
	data() {
		return {
			NETWORK_ID: NETWORKID,
			web3: Web3,
			// VRPressToken: '',
			myAddress: '',
			assets: [],
			onSaleAssets: [],
			nickName: '',
			selfintro: '',
			avatar: '',
			background: '',
			showUpBg: false,
			objData: null,
		};
	},
	methods: {
		async getWeb3() {
			var web3;
			if (window.ethereum) {
				// Modern dapp browsers
				web3 = new Web3(window.ethereum);
				try {
					// metamaskが開いて権限許可を尋ねる
					await window.ethereum.enable();
				} catch (error) {
					// 拒否した場合に入ってくる
					console.log('denied');
				}
			} else if (window.web3) {
				// Legacy dapp browsers...
				web3 = new Web3(window.web3.currentProvider);
			} else {
				// this.selectedModal = this.MODALS.METAMASK
				// this.openModal({
				// 	title: "confirm",
				// 	isOnlyConfirm: true
				// })
			}

			web3 = new Web3(window.web3.currentProvider);
			return web3;
		},
		getDeployData() {
			return require(`../../../zos.dev-${this.NETWORK_ID}.json`);
		},
		filterByForSale(arrayList, value) {
			return arrayList.filter((item) => item.forSale == value);
		},
		gotoEdit() {
			this.$router.push('/edit');
		},

		async getStstoken() {
			let res = await ststoken(getAuthorization());
			console.log(res.data.data.SecurityToken);
			let data = res.data.data;
			console.log(data.SecurityToken);
			let client = new OSS({
				accessKeyId: 'LTAI4Fxv55cArEHyaNoK7L7b', //已经替换为+1的（√）
				accessKeySecret: 'fFVmSCAgySqhuVkdHz7nbAbWJ167DW', //需要替换为+1的（x）
				bucket: 'haichain-nfts',
				stsToken: data.SecurityToken,
				secure: true,
			});

			console.log(188, client);
			this.objData = data;
		},
		//上传用户背景图
		handleBackgroundUpload(file) {
			this.background = file;
			this.Upload(file);
			return false;
		},
		//上传文件
		Upload(file) {
			console.log(file);
			let store = new OSS({
				accessKeyId: this.objData.AccessKeyId,
				accessKeySecret: this.objData.AccessKeySecret,
				bucket: 'haichain-nfts',
				stsToken: this.objData.SecurityToken,
				region: 'oss-cn-hangzhou',
				secure: true,
			});
			//let store = new OSS(this.objData);

			store
				.multipartUpload(
					//第一个参数可以设置自定义的路径
					'/userInfo/' + file.name,
					// file.name,
					file,
					{
						//获取进度条的值
						progress: (p) => {
							console.log(p);
						},
					}
				)
				.then(
					//处理成功
					(result) => {
						//处理签名地址
						store.signatureUrl(result.name);
						console.log(result);
					}
				)
				.catch((err) => {
					console.log(err);
				});
		},
	},
	async mounted() {
		this.getStstoken();

		this.web3 = await this.getWeb3();
		await this.web3.eth.getAccounts((error, accounts) => {
			if (error) {
				console.log('error');
				return;
			}
			this.myAddress = accounts[0];
			console.log('my address is' + this.myAddress);
		});
		this.nickName = JSON.parse(localStorage.getItem('UserInfo')).nickname;
		this.selfintro = JSON.parse(localStorage.getItem('UserInfo')).selfintro;
		this.avatar = JSON.parse(localStorage.getItem('UserInfo')).avatar;
		this.background = JSON.parse(
			localStorage.getItem('UserInfo')
		).background;
		const contractData = require('../../../' +
			CONTRACTBUILD +
			'/contracts/AssetToken.json');
		const deployData = this.getDeployData();
		// const tokenProxyAdresses = deployData.proxies["marketplace/AssetToken"]
		const VRPressTokenAddress = deployData.contracts.AssetToken.address;
		// console.log(VRPressTokenAddress);

		const VRPressToken = await new this.web3.eth.Contract(
			contractData.abi,
			// tokenProxyAdresses[tokenProxyAdresses.length - 1].address
			VRPressTokenAddress
		);

		const myNfts = await VRPressToken.methods
			.tokensOfOwner(this.myAddress)
			.call();
		// console.log(myNfts)

		for (let i = 0; i < myNfts.length; i++) {
			const token = await VRPressToken.methods.getToken(myNfts[i]).call();
			const asset = {
				id: token['0'],
				name: token['1'],
				uri: token['3'],
				price: +this.web3.utils.fromWei(token[4].toString(), 'ether'),
				forSale: token['5'],
				owner: token['6'],
				avatar: this.avatar,
			};
			this.assets.push(asset);
		}
		//nft列表
		// console.log(this.assets);
		this.onSaleAssets = this.filterByForSale(this.assets, 1);
	},
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.imgBg {
	img[src=''],
	img:not([src]) {
		opacity: 0;
	}
}

::-webkit-scrollbar {
	width: 0 !important;
}
::-webkit-scrollbar {
	width: 0 !important;
	height: 0;
}
</style>

<style>
.ivu-tabs {
	overflow-x: hidden !important;
	overflow-y: scroll !important;
}
</style>
